package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.AcquireAccountAuthTokenReq;
import net.ib.mntalk.protocol.Session.AcquireAccountAuthTokenRes;
import net.ib.mntalk.protocol.Session.AcquireUserAuthTokenReq;
import net.ib.mntalk.protocol.Session.AcquireUserAuthTokenRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class AcquireUserAuthTask extends AsyncNetTask{

	private AcquireUserAuthTokenReq mAcquireUserAuthTokenReq;
	
	public AcquireUserAuthTask(Context context, Handler handler, AcquireUserAuthTokenReq acquireUserAuthTokenReq) {
		super(context, handler);
		this.mAcquireUserAuthTokenReq = acquireUserAuthTokenReq;
	}
	

	protected TcpEnvelope onPreExecute() {
		TcpEnvelope revelop = new TcpEnvelope.Builder()
		.setType(TcpEnvelope.REQUEST)
		.setMessage(mAcquireUserAuthTokenReq)
		.setMethodId(Session.Registration.AcquireUserAuthToken)
		.build();
		
		return revelop;
	}

	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.v("AcquireUserAuthTask.onPostExecute() - STT");
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		AcquireUserAuthTokenRes res = (AcquireUserAuthTokenRes) resultEnvelope.getMessage();
		
		if(res.getResponseCode() == Common.SUCCESS){
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ACQUIRE_USER_AUTH_SUCCESS);
			msg.obj = res;
			mUiHandler.sendMessageAtFrontOfQueue(msg);
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ACQUIRE_USER_AUTH_FAIL));
		}
	}
}
